package flc.ast.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.picselect.entity.SelectMediaEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.AlbumActivity;
import flc.ast.activity.MoveActivity;
import flc.ast.activity.PlayLandscapeActivity;
import flc.ast.activity.PrivacyActivity;
import flc.ast.adapter.FolderAdapter;
import flc.ast.adapter.VideoAdapter;
import flc.ast.adapter.VideoAdapter1;
import flc.ast.databinding.FragmentPlayBinding;
import flc.ast.dialog.AddFolderDialog;
import flc.ast.dialog.ChangePasswordDialog;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.InputAnswerDialog;
import flc.ast.dialog.InputPasswordDialog;
import flc.ast.dialog.RankDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.dialog.SetAnswerDialog;
import flc.ast.dialog.SetPasswordDialog;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.SPUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PlayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PlayFragment extends BaseNoModelFragment<FragmentPlayBinding> {

    private VideoAdapter videoAdapter;
    private VideoAdapter1 videoAdapter1;
    private FolderAdapter folderAdapter;
    private List<String> listAll = new ArrayList<>();//全部数据
    private List<String> listShow = new ArrayList<>();//搜索后展示的数据
    private boolean hasLineStyle;
    private BasePopupView rankPopup;
    private RankDialog rankDialog;
    private int selPosition;
    private String pwd;


    @Override
    protected int onCreate() {
        return R.layout.fragment_play;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.ivPrivacy.setOnClickListener(this);
        mDataBinding.ivEdit.setOnClickListener(this);
        mDataBinding.ivLayout.setOnClickListener(this);
        mDataBinding.ivSearch.setOnClickListener(this);

        mDataBinding.rvFolderList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        folderAdapter = new FolderAdapter();
        mDataBinding.rvFolderList.setAdapter(folderAdapter);
        folderAdapter.setOnItemClickListener(this);

        mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext));
        videoAdapter = new VideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemEdit);
        videoAdapter.setOnItemChildClickListener(this);
        videoAdapter.setOnItemClickListener(this);

        videoAdapter1 = new VideoAdapter1();
        videoAdapter1.addChildClickViewIds(R.id.ivVideoItemEdit);
        videoAdapter1.setOnItemChildClickListener(this);
        videoAdapter1.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPrivacy://加密文件
                //是否完成设置密码
                boolean isSetPassword = SPUtil.getBoolean(getContext(), Content.isHavePassword, false);
                if (isSetPassword) {
                    showInputPasswordDialog();
                } else {
                    showSetPasswordDialog();
                }
                break;
            case R.id.ivEdit://编辑
                showRankDialog();
                break;
            case R.id.ivSearch://搜索
                searchVideo();
                break;
            case R.id.ivLayout://布局
                if (hasLineStyle) {
                    mDataBinding.ivLayout.setImageResource(R.drawable.zhankl);
                    mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 3));
                    mDataBinding.rvVideoList.setAdapter(videoAdapter1);
                } else {
                    mDataBinding.ivLayout.setImageResource(R.drawable.zhank);
                    mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext));
                    mDataBinding.rvVideoList.setAdapter(videoAdapter);
                }
                hasLineStyle = !hasLineStyle;
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == folderAdapter) {
            PrivacyActivity.path = Content.myFolder + "/" + FileUtils.getFileNameNoExtension(folderAdapter.getItem(position));
            startActivity(PrivacyActivity.class);
        } else {
            PlayLandscapeActivity.listPlay = listShow;
            PlayLandscapeActivity.selPlayPos = position;
            startActivity(PlayLandscapeActivity.class);
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoItemEdit://编辑
                selPosition = position;
                showEditDialog();
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
        getFolderData();
    }

    private void getData() {
        listAll.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listAll.add(file.getPath());
            }
        }
        if (listAll.size() > 0) {
            searchVideo();
            mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
            mDataBinding.tvVideoNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
        }
    }

    //搜索视频
    private void searchVideo() {
        listShow.clear();
        String text = mDataBinding.etSearch.getText().toString();
        if (TextUtils.isEmpty(text)) {
            listShow.addAll(listAll);
        } else {
            listShow.clear();
            for (String bean : listAll) {
                if (FileUtils.getFileName(bean).contains(text)) {
                    listShow.add(bean);
                }
            }
        }
        videoAdapter.setList(listShow);
        videoAdapter1.setList(listShow);
        if (listShow.size() > 0) {
            mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
        }
    }

    private void getFolderData() {
        List<String> listData = new ArrayList<>();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myFolder;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listData.add(file.getPath());
            }
        }
        if (listData.size() > 0) {
            folderAdapter.setList(listData);
            mDataBinding.rvFolderList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvFolderList.setVisibility(View.GONE);
        }
    }

    private void showRankDialog() {
        if (rankDialog == null) rankDialog = new RankDialog(mContext);
        rankPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivEdit).hasShadowBg(false) // 去掉半透明背景
                .asCustom(rankDialog);
        rankDialog.setListener(new RankDialog.Ilistener() {
            @Override
            public void clickAddFolder() {
                showAddFolderDialog();
            }

            @Override
            public void clickImport() {
                AlbumActivity.path = Content.myVideo;
                startActivity(AlbumActivity.class);
            }

            @Override
            public void clickRankToName() {
                sortFileBeanList(1);
            }

            @Override
            public void clickRankToSize() {
                sortFileBeanList(2);
            }

            @Override
            public void clickRankToTime() {
                sortFileBeanList(3);
            }
        });
        rankPopup.show();
    }

    public void sortFileBeanList(int sortBy) {
        switch (sortBy) {
            case 1:
                // 按名称排序
                Collections.sort(listShow, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        return FileUtils.getFileName(o1).compareTo(FileUtils.getFileName(o2));
                    }
                });
                break;
            case 2:
                // 按大小排序
                Collections.sort(listShow, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        long length1 = new File(o1).length();
                        long length2 = new File(o2).length();
                        return Long.compare(length1, length2);
                    }
                });
                break;
            case 3:
                // 按时间排序
                Collections.sort(listShow, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        Date date1 = null;
                        Date date2 = null;
                        date1 = new Date(FileUtils.getFileLastModified(o1));
                        date2 = new Date(FileUtils.getFileLastModified(o2));
                        return date1.compareTo(date2);
                    }
                });
                break;
            default:
                break;
        }
        videoAdapter.setList(listShow);
        videoAdapter1.setList(listShow);
    }

    private void showEditDialog() {
        EditDialog dialog = new EditDialog(mContext);
        dialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickRename() {
                showRenameDialog();
            }

            @Override
            public void clickPrivacy() {
                String filePath = FileUtil.generateFilePath(Content.myPrivacy, "." + FileUtils.getFileExtension(listShow.get(selPosition)));
                FileUtils.copy(listShow.get(selPosition), filePath);
                ToastUtils.showShort(getString(R.string.privacy_suc));
            }

            @Override
            public void clickMove() {
                MoveActivity.videoPath = listShow.get(selPosition);
                startActivity(MoveActivity.class);
            }

            @Override
            public void clickShare() {

            }

            @Override
            public void clickDelete() {

            }
        });
        dialog.show();
    }

    private void showRenameDialog() {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listShow.get(selPosition), name + "." + FileUtils.getFileExtension(listShow.get(selPosition)));
                getData();
            }
        });
        dialog.show();
    }

    private void showSetPasswordDialog() {
        SetPasswordDialog passwordDialog = new SetPasswordDialog(mContext);
        passwordDialog.setListener(new SetPasswordDialog.Ilistener() {
            @Override
            public void click(String password) {
                pwd = password;
                showSetAnswerDialog();
            }
        });
        passwordDialog.show();
    }

    private void showSetAnswerDialog() {
        SetAnswerDialog answerDialog = new SetAnswerDialog(mContext);
        answerDialog.setListener(new SetAnswerDialog.Listener() {
            @Override
            public void setPassword(String question, String answer) {
                //记录密码
                SPUtil.putBoolean(getContext(), Content.isHavePassword, true);
                SPUtil.putString(getContext(), Content.myPassword, pwd);
                SPUtil.putString(getContext(), Content.myProblem, question);
                SPUtil.putString(getContext(), Content.myAnswer, answer);
            }
        });
        answerDialog.show();
    }

    private void showInputPasswordDialog() {
        InputPasswordDialog passwordDialog = new InputPasswordDialog(mContext);
        passwordDialog.setListener(new InputPasswordDialog.Ilistener() {
            @Override
            public void clickForget() {
                showInputAnswerDialog();
            }
        });
        passwordDialog.show();
    }

    private void showInputAnswerDialog() {
        InputAnswerDialog answerDialog = new InputAnswerDialog(mContext);
        answerDialog.setListener(new InputAnswerDialog.Listener() {
            @Override
            public void changePassword() {
                showChangePasswordDialog();
            }
        });
        answerDialog.show();
    }

    private void showChangePasswordDialog() {
        ChangePasswordDialog passwordDialog = new ChangePasswordDialog(mContext);
        passwordDialog.setListener(new ChangePasswordDialog.Ilistener() {
            @Override
            public void click(String password) {
                //记录密码
                SPUtil.putString(getContext(), Content.myPassword, password);
            }
        });
        passwordDialog.show();
    }

    private void showAddFolderDialog() {
        AddFolderDialog dialog = new AddFolderDialog(mContext);
        dialog.setListener(new AddFolderDialog.Ilistener() {
            @Override
            public void clickAddFolder(String name) {
                String path = PathUtils.getFilesPathExternalFirst() + Content.myFolder + "/" + name;
                if (FileUtils.isFileExists(path)) {
                    ToastUtils.showShort(getString(R.string.folder_is_exist));
                } else {
                    FileUtils.createOrExistsDir(path);
                    ToastUtils.showShort(getString(R.string.add_folder_suc));
                }
                getFolderData();
            }
        });
        dialog.show();
    }

}